package com.yunshu.yunshuapp.xianhuo;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.constant.WBConstants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.openapi.BaseReq;
import com.tencent.mm.sdk.openapi.BaseResp;
import com.tencent.mm.sdk.openapi.ConstantsAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.tencent.tauth.UiError;
import com.yunshu.yunshuapp.ImageActivity;
import com.yunshu.yunshuapp.NavigationBar;
import com.yunshu.yunshuapp.R;
import com.yunshu.yunshuapp.WebviewWithShareActivity;
import com.yunshu.yunshuapp.kuaixun.KuaixunListActivity;
import com.yunshu.yunshuapp.network.YSCallback;
import com.yunshu.yunshuapp.network.YSRequest;
import com.yunshu.yunshuapp.user.YSUser;
import com.yunshu.yunshuapp.utils.YSUtils;

import java.io.IOException;
import java.util.ArrayList;

public class XianhuoDetailActivity2 extends WebviewWithShareActivity implements Toolbar.OnMenuItemClickListener {

    protected Xianhuo model;
    private RelativeLayout maskView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NavigationBar navibar = (NavigationBar) findViewById(R.id.navigationBar);
        navibar.setOnMenuItemClickListener(this);

        Bundle bundle = this.getIntent().getExtras();
        String xianhuoString = (String) bundle.get("xianhuo");
        if (xianhuoString != null) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                model = mapper.readValue(xianhuoString, Xianhuo.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        findViewById(R.id.shareToolbar).setVisibility(View.GONE);

        maskView = (RelativeLayout) findViewById(R.id.maskLayout);
        RelativeLayout timeLine = (RelativeLayout) findViewById(R.id.timeline);
        RelativeLayout session = (RelativeLayout)findViewById(R.id.session);
        RelativeLayout weibo = (RelativeLayout)findViewById(R.id.weibo);
        Button cancelButton = (Button)findViewById(R.id.cancelButton);
        View qqButton = findViewById(R.id.qq);
        View qzoneButton = findViewById(R.id.qzone);
        Button edit = (Button) findViewById(R.id.editButton);
        if (this.model.getUserid() != null && this.model.getUserid().equals(YSUser.instance().getUid())){
            edit.setVisibility(View.VISIBLE);
            edit.setOnClickListener(this);
            LinearLayout buttonContainer = (LinearLayout) findViewById(R.id.shareButtonsContainer);
            ViewGroup.LayoutParams layoutParmas = buttonContainer.getLayoutParams();
            layoutParmas.height *= 240.0/191.0;
            buttonContainer.setLayoutParams(layoutParmas);
        }else{
//            buttonContainer.getLayoutParams().height *= 1.91;
            edit.setVisibility(View.GONE);
        }

        timeLine.setOnClickListener(this);
        session.setOnClickListener(this);
        weibo.setOnClickListener(this);
        cancelButton.setOnClickListener(this);
        qqButton.setOnClickListener(this);
        qzoneButton.setOnClickListener(this);
    }


    public void onClick(View view){
        if (view.getId() == R.id.timeline){
            this.share2WX(SendMessageToWX.Req.WXSceneTimeline);

        }else if(view.getId() == R.id.weibo){
            this.share2Weibo();
        }else if(view.getId() == R.id.session){
            this.share2WX(SendMessageToWX.Req.WXSceneSession);
        }else if(view.getId() == R.id.qq){
            this.share2QQ();
        }else if(view.getId() == R.id.qzone){
            this.share2QZone();
        }else if(view.getId() == R.id.cancelButton){
            maskView.setVisibility(View.INVISIBLE);
        }else if(view.getId() == R.id.editButton){
            maskView.setVisibility(View.INVISIBLE);
            Intent intent = new Intent();
            intent.setClass(XianhuoDetailActivity2.this, AddBaojiaActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("model",this.model.serializeToString());
            intent.putExtras(bundle);
            startActivityForResult(intent,0);
        }
    }

    protected void refresh() {

        webView.setWebViewClient(new WebViewClient() {
            @Override public void onPageFinished(WebView view, String url1) {
                super.onPageFinished(view, url1);

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("tel:")){
                    Intent intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse(url));
                    startActivity(intent);
                } else if(url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url);
                }
                return true;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
            {
                if (failingUrl.contains("#")) {
                    String[] temp = failingUrl.split("#");
                    webView.loadUrl(temp[0]);
                    try {
                        Thread.sleep(400);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    webView.loadUrl(failingUrl);
                }
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                if (request.getUrl().toString().contains("#")) {
                    String failingUrl = request.getUrl().toString();
                    String[] temp = failingUrl.split("#");
                    webView.loadUrl(temp[0]);
                    try {
                        Thread.sleep(400);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    webView.loadUrl(failingUrl);
                }
            }
        });

        String newUrl = url ;// .substring(0, url.indexOf('#'));
        webView.loadUrl(newUrl);


    }

    protected void share2Weibo() {

        if (!mWeiboShareAPI.isWeiboAppInstalled()) {
            Toast.makeText(this, "未安装微博！", Toast.LENGTH_LONG).show();
            return;
        }

        final WeiboMultiMessage weiboMessage = new WeiboMultiMessage();//初始化微博的分享消息

        TextObject textObject = new TextObject();
        textObject.text = model.getAdvert();
        weiboMessage.textObject = textObject;
//        loadingView.setVisibility(View.VISIBLE);
//        loadingView.load();

        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = YSUtils.generateGUID();
        mediaObject.title = model.getChannelname()+model.getCompany()+"今日报价";
        mediaObject.description = model.getAdvert();
        // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        mediaObject.setThumbImage(bitmap);
        mediaObject.actionUrl = shareURL();
        mediaObject.defaultText = "云数智惠";
        weiboMessage.mediaObject = mediaObject;
        final SendMultiMessageToWeiboRequest request1 = new SendMultiMessageToWeiboRequest();
        request1.transaction = String.valueOf(System.currentTimeMillis());
        request1.multiMessage = weiboMessage;
        qqSharing = false;
        boolean b = mWeiboShareAPI.sendRequest(XianhuoDetailActivity2.this, request1);//发送请求消息到微博，唤起微博分享界面
//        loadingView.setVisibility(View.VISIBLE);
//        loadingView.load();
//        mImageLoader.loadImage(model.getImageUrl(), new ImageLoadingListener() {
//            @Override
//            public void onLoadingStarted(String s, View view) { }
//
//            @Override
//            public void onLoadingFailed(String s, View view, FailReason failReason) {
//                loadingView.setVisibility(View.INVISIBLE);
//                boolean b = mWeiboShareAPI.sendRequest(WebviewWithShareActivity.this,request1);//发送请求消息到微博，唤起微博分享界面
//            }
//
//            @Override
//            public void onLoadingComplete(String s, View view, Bitmap bitmap) {
//                loadingView.setVisibility(View.INVISIBLE);
//
//                WebpageObject mediaObject = new WebpageObject();
//                mediaObject.identify = YSUtils.generateGUID();
//                mediaObject.title = model.getTitle();
//                mediaObject.description = model.getTitle();
//                // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
//                // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
//                float w = bitmap.getWidth();
//                float h = bitmap.getHeight();
//                bitmap = YSUtils.ratio(bitmap,100, 100/w * h);
//                mediaObject.setThumbImage(bitmap);
//                mediaObject.actionUrl = shareURL();
//                mediaObject.defaultText = "云数智惠";
//                weiboMessage.mediaObject = mediaObject;
//                Boolean valiad = weiboMessage.checkArgs();
//                SendMultiMessageToWeiboRequest request1 = new SendMultiMessageToWeiboRequest();
//                request1.transaction = String.valueOf(System.currentTimeMillis());
//                request1.multiMessage = weiboMessage;
//                qqSharing = false;
//                boolean b = mWeiboShareAPI.sendRequest(WebviewWithShareActivity.this,request1);//发送请求消息到微博，唤起微博分享界面
//                System.out.println("11111"+b);
//            }
//
//            @Override
//            public void onLoadingCancelled(String s, View view) {
//
//            }
//        });

    }

    protected String shareURL() {
        return url + "&fromApp=1";
    }

    protected void share2QQ() {
//        if (!mTencent.is()){
//            Toast.makeText(this, "未安装QQ!", Toast.LENGTH_LONG).show();
//        }
        Bundle bundle = new Bundle();
        //这条分享消息被好友点击后的跳转URL。
        bundle.putString(QQShare.SHARE_TO_QQ_TARGET_URL, this.shareURL());
        //分享的标题。注：PARAM_TITLE、PARAM_IMAGE_URL、PARAM_SUMMARY不能全为空，最少必须有一个是有值的。
        bundle.putString(QQShare.SHARE_TO_QQ_TITLE, model.getChannelname()+"今日报价");
        bundle.putString(QQShare.SHARE_TO_QQ_SUMMARY, model.getAdvert());

        //分享的图片URL
        if (model.getKucunpic() != null ) {
            bundle.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, model.getKucunpic());
        }else{
            bundle.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "http://www.yunshutech.com/pictureService/showImage.action?type=0&filename=ccbe074f-b85f-454b-bc25-b1f977046222.png");
        }
        //分享的消息摘要，最长50个字
//        bundle.putString(QQShare.PARAM_SUMMARY, "测试");

        bundle.putString(QQShare.SHARE_TO_QQ_APP_NAME, "云数智惠");
        //标识该消息的来源应用，值为应用名称+AppId。
//        bundle.putString(QQShare.PARAM_APP_SOURCE, "星期几" + YSUtils.QQAPPID);

        bundle.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);

        qqSharing = true;
        mTencent.shareToQQ(this, bundle, this);
    }

    public void share2QZone() {
        final Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);//类型
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, model.getChannelname()+model.getCompany()+"今日报价");//标题
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, model.getAdvert());//概要
        params.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, "云数智惠");
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, this.shareURL());
        if (this.model.getKucunpic() != null) {
            //下面这个必须加上  不然无法调动 qq空间
            ArrayList<String> imageUrls = new ArrayList<String>();
            imageUrls.add(this.model.getKucunpic());
            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);
        } else {
            ArrayList<String> imageUrls = new ArrayList<String>();
            imageUrls.add("http://www.yunshutech.com/pictureService/showImage.action?type=0&filename=ccbe074f-b85f-454b-bc25-b1f977046222.png");
            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);
        }
        mTencent.shareToQzone(XianhuoDetailActivity2.this, params, XianhuoDetailActivity2.this);
    }

    protected void share2WX(final int WXScene) {
        if (!api.isWXAppInstalled()) {
            Toast.makeText(this, "未安装微信!", Toast.LENGTH_LONG).show();
        }

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = this.shareURL();

        final WXMediaMessage msg = new WXMediaMessage(webpage);
        if (WXScene == SendMessageToWX.Req.WXSceneSession){
            msg.title = model.getChannelname()+model.getCompany()+"今日报价";
        }else{
            msg.title = model.getAdvert();
        }
        msg.description = model.getAdvert();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        msg.setThumbImage(bitmap);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
//                    req.transaction = ""
        req.message = msg;
        req.scene = WXScene;
        qqSharing = false;
//        boolean ret = api.sendReq(req);
        mImageLoader.loadImage(model.getKucunpic(), new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String s, View view) {

            }

            @Override
            public void onLoadingFailed(String s, View view, FailReason failReason) {
                loadingView.setVisibility(View.INVISIBLE);

                SendMessageToWX.Req req = new SendMessageToWX.Req();
//                    req.transaction = ""
                req.message = msg;
                req.scene = WXScene;
                qqSharing = false;
                boolean ret = api.sendReq(req);
            }

            @Override
            public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                loadingView.setVisibility(View.INVISIBLE);

                // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
                float w = bitmap.getWidth();
                float h = bitmap.getHeight();
                bitmap = YSUtils.ratio(bitmap, 100, 100 / w * h);
                msg.setThumbImage(bitmap);
                SendMessageToWX.Req req = new SendMessageToWX.Req();
//                    req.transaction = ""
                req.message = msg;
                req.scene = WXScene;
                qqSharing = false;
                boolean ret = api.sendReq(req);
            }

            @Override
            public void onLoadingCancelled(String s, View view) {
                loadingView.setVisibility(View.INVISIBLE);

                SendMessageToWX.Req req = new SendMessageToWX.Req();
//                    req.transaction = ""
                req.message = msg;
                req.scene = WXScene;
                qqSharing = false;
                boolean ret = api.sendReq(req);
            }
        });

    }

    @Override
    public void onReq(BaseReq req) {
        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                System.out.println("COMMAND_GETMESSAGE_FROM_WX");
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
//                goToShowMsg((ShowMessageFromWX.Req) req);
                System.out.println("COMMAND_SHOWMESSAGE_FROM_WX");

                break;
            default:
                break;
        }
    }

    @Override
    public void onResp(BaseResp resp) {
        int result = 0;

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                Toast.makeText(this, "成功分享到微信", Toast.LENGTH_LONG).show();

                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                Toast.makeText(this, "取消分享到微信", Toast.LENGTH_LONG).show();

                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Toast.makeText(this, "分享到微信失败", Toast.LENGTH_LONG).show();

                break;
            default:
                Toast.makeText(this, "分享到微信失败", Toast.LENGTH_LONG).show();

                break;
        }

        Toast.makeText(this, result, Toast.LENGTH_LONG).show();
    }

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mWeiboShareAPI.handleWeiboResponse(intent, this); //当前应用唤起微博分享后，返回当前应用
    }

    public void onResponse(BaseResponse baseResp) {//接收微客户端博请求的数据。

        switch (baseResp.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(this, "成功分享到微博", Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toast.makeText(this, "取消分享到微博", Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(this, "分享到微博失败", Toast.LENGTH_LONG).show();
                break;
        }

    }

    @Override
    public void onComplete(Object o) {
        Toast.makeText(this, "成功分享到QQ", Toast.LENGTH_LONG).show();
    }

    public void onError(UiError e) {

        Toast.makeText(this, "分享到QQ失败", Toast.LENGTH_LONG).show();
    }

    public void onCancel() {

        Toast.makeText(this, "取消分享到QQ", Toast.LENGTH_LONG).show();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        loadingView.setVisibility(View.INVISIBLE);
        if (null != mTencent && qqSharing)
            mTencent.onActivityResultData(requestCode, resultCode, data, this);
    }

    protected void updateLoveButton() {

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_share2 , menu);
        return true;
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_share2:
                maskView.setVisibility(View.VISIBLE);
                break;
            default:break;
        }
        return true;
    }

}